package pannel.order;

import pannel.product.Product;
import pannel.product.ProductDao;
import system.BasePage;
import pannel.user.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;

public class UserOrderPage extends BasePage {
    private DefaultTableModel model;
    private JTable table;
    private int currentPage = 1;
    private int pageSize = 10;
    private JLabel pageInfoLabel;
    private OrderDao orderDao;
    private int totalRecords = 0;

    public UserOrderPage(User user) {
        super(user);
        orderDao = new OrderDao();
        initPageContent();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("我的订单");
        setupContent();
        refreshTable();
    }

    private void setupContent() {
        contentArea.setLayout(new BorderLayout());

        // 表格设置
        String[] columnNames = {"订单ID", "商品", "数量", "总价", "状态", "创建时间", "操作"};
        model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                // 只允许操作列可编辑
                return column == 6;
            }
        };
        table = new JTable(model);

        // 设置表格的行高
        table.setRowHeight(35);

        // 设置操作列的渲染器和编辑器
        table.getColumnModel().getColumn(6).setCellRenderer(new ButtonRenderer());
        table.getColumnModel().getColumn(6).setCellEditor(new ButtonEditor());

        // 分页面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        pageInfoLabel = new JLabel();
        paginationPanel.add(prevButton);
        paginationPanel.add(pageInfoLabel);
        paginationPanel.add(nextButton);

        // 按钮事件
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                refreshTable();
            }
        });

        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                refreshTable();
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);
        contentArea.add(scrollPane, BorderLayout.CENTER);
        contentArea.add(paginationPanel, BorderLayout.SOUTH);
    }

    // 按钮渲染器
    class ButtonRenderer extends JButton implements javax.swing.table.TableCellRenderer {
        public ButtonRenderer() {
            setOpaque(true);
            setFocusPainted(false);
            setBorderPainted(true);
            setBackground(new Color(245, 245, 245));
            setForeground(new Color(51, 51, 51));
            setFont(new Font("微软雅黑", Font.PLAIN, 12));
            setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            setText(value.toString());
            if (isSelected) {
                setBackground(new Color(235, 235, 235));
            } else {
                setBackground(new Color(245, 245, 245));
            }
            return this;
        }
    }

    // 按钮编辑器
    class ButtonEditor extends AbstractCellEditor implements javax.swing.table.TableCellEditor {
        private JButton button;
        private String label;
        private boolean isPushed;

        public ButtonEditor() {
            button = new JButton();
            button.setOpaque(true);
            button.setFocusPainted(false);
            button.setBorderPainted(true);
            button.setBackground(new Color(245, 245, 245));
            button.setForeground(new Color(51, 51, 51));
            button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            button.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
            
            button.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    button.setBackground(new Color(235, 235, 235));
                }

                public void mouseExited(java.awt.event.MouseEvent evt) {
                    button.setBackground(new Color(245, 245, 245));
                }
            });
            
            button.addActionListener(e -> {
                fireEditingStopped();
                int row = table.getSelectedRow();
                if (row != -1) {
                    int orderId = (Integer) table.getValueAt(row, 0);
                    String status = (String) table.getValueAt(row, 4);
                    
                    if (status.equals(Order.STATUS_PENDING)) {
                        handlePayment(orderId);
                    } else {
                        showOrderDetail(row);
                    }
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
            label = value.toString();
            button.setText(label);
            isPushed = true;
            return button;
        }

        @Override
        public Object getCellEditorValue() {
            isPushed = false;
            return label;
        }

        @Override
        public boolean stopCellEditing() {
            isPushed = false;
            return super.stopCellEditing();
        }
    }

    private void handlePayment(int orderId) {
        int confirm = JOptionPane.showConfirmDialog(
            this,
            "确认支付该订单？",
            "支付确认",
            JOptionPane.YES_NO_OPTION
        );
        
        if (confirm == JOptionPane.YES_OPTION) {
            try {
                if (orderDao.updateStatus(orderId, Order.STATUS_PAID)) {
                    JOptionPane.showMessageDialog(this, "支付成功！");
                    refreshTable();
                } else {
                    JOptionPane.showMessageDialog(this, "支付失败，请重试");
                }
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "支付失败：" + e.getMessage());
            }
        }
    }

    private void showOrderDetail(int row) {
        // 创建自定义对话框
        JDialog dialog = new JDialog(JOptionPane.getFrameForComponent(this), "订单详情", true);
        dialog.setLayout(new BorderLayout(10, 10));
        
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(15, 15));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        // 创建左侧信息面板
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 15));
        
        // 添加订单信息
        String[] labels = {
            "订单编号：" + table.getValueAt(row, 0),
            "商品名称：" + table.getValueAt(row, 1),
            "购买数量：" + table.getValueAt(row, 2),
            "订单金额：" + table.getValueAt(row, 3),
            "订单状态：" + table.getValueAt(row, 4),
            "创建时间：" + table.getValueAt(row, 5)
        };
        
        for (String text : labels) {
            JLabel label = new JLabel(text);
            label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            label.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
            label.setAlignmentX(Component.LEFT_ALIGNMENT);
            infoPanel.add(label);
        }
        
        // 创建右侧图片面板
        JPanel imagePanel = new JPanel(new BorderLayout());
        imagePanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), 
            "商品图片",
            javax.swing.border.TitledBorder.LEFT,
            javax.swing.border.TitledBorder.TOP,
            new Font("微软雅黑", Font.PLAIN, 12)
        ));
        
        // 获取商品图片
        try {
            // 通过订单ID获取商品信息
            int orderId = (Integer) table.getValueAt(row, 0);
            Order order = orderDao.getOrderById(orderId);
            Product product = new ProductDao().getById(order.getProductId());
            
            if (product != null && product.getImagePath() != null) {
                ImageIcon originalIcon = new ImageIcon(product.getImagePath());
                Image image = originalIcon.getImage();
                // 设置图片大小为200x200
                Image scaledImage = image.getScaledInstance(200, 200, Image.SCALE_SMOOTH);
                JLabel imageLabel = new JLabel(new ImageIcon(scaledImage));
                imageLabel.setHorizontalAlignment(JLabel.CENTER);
                imagePanel.add(imageLabel, BorderLayout.CENTER);
            } else {
                JLabel noImageLabel = new JLabel("暂无图片");
                noImageLabel.setHorizontalAlignment(JLabel.CENTER);
                noImageLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
                imagePanel.add(noImageLabel, BorderLayout.CENTER);
            }
        } catch (Exception e) {
            JLabel errorLabel = new JLabel("图片加载失败");
            errorLabel.setHorizontalAlignment(JLabel.CENTER);
            errorLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            imagePanel.add(errorLabel, BorderLayout.CENTER);
        }
        
        // 添加到主面板
        mainPanel.add(infoPanel, BorderLayout.CENTER);
        mainPanel.add(imagePanel, BorderLayout.EAST);
        
        // 创建确定按钮
        JButton okButton = new JButton("确定");
        okButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        okButton.addActionListener(e -> dialog.dispose());
        
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(okButton);
        
        // 添加组件到对话框
        dialog.add(mainPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 设置对话框大小和位置
        dialog.setSize(600, 400);
        dialog.setLocationRelativeTo(this);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    }

    private void refreshTable() {
        SwingUtilities.invokeLater(() -> {
            try {
                List<Order> orders = orderDao.pageQueryByUser(getCurrentUser().getId(), currentPage, pageSize);
                totalRecords = orderDao.getUserOrderCount(getCurrentUser().getId());

                model.setRowCount(0);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (Order order : orders) {
                    model.addRow(new Object[]{
                            order.getId(),
                            order.getProductName(),
                            order.getQuantity(),
                            String.format("￥%.2f", order.getTotalPrice()),
                            order.getStatus(),
                            sdf.format(order.getCreateTime()),
                            order.getStatus().equals(Order.STATUS_PENDING) ? "去支付" : "查看详情"
                    });
                }

                updatePageInfo();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "获取订单数据失败：" + e.getMessage());
            }
        });
    }

    private void updatePageInfo() {
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
        pageInfoLabel.setText(String.format("第 %d/%d 页  共%d条记录", currentPage, totalPages, totalRecords));
    }
} 